package com.teng.dataStructure.arrayQueue;

import java.util.Scanner;

/**
* @Author liangtl
* @Date 2022/6/26 17:23
* @Param
* @Description 队列：数组模拟队列
*/
public class ArraryQueueDemo {
    public static void main(String[] args) throws Exception {

        //初始化
        ArrayQueue arrayQueue = new ArrayQueue(3);
        //接收用户输入
        String key;
        Scanner scanner = new Scanner(System.in);
        //显示菜单
        boolean loop = true;
        while (loop) {
            System.out.println("s(show): 显示队列数据");
            System.out.println("h(head): 获取头数据");
            System.out.println("a(add): 添加一个数据至队列");
            System.out.println("g(get): 从队列中取出一个数据");
            System.out.println("e(exit): 退出程序");
            key = String.valueOf(scanner.next().charAt(0));
            switch (key) {
                case "s":
                    arrayQueue.showQueue();
                    break;
                case "h":
                    System.out.println("队列的头数据为：" + arrayQueue.getFront());
                    break;
                case "a":
                    System.out.println("请输入需要添加的数据");
                    arrayQueue.addQueue(scanner.nextInt());
                    break;
                case "g":
                    arrayQueue.getQueue();
                    break;
                case "e":
                    scanner.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出");
    }
}

class ArrayQueue {
    private int front; //队列头,指向队列头的前一个位置
    private int rear; //队列尾
    private int maxSize; //队列最大容量
    private int[] arr; //模拟队列

    //创建队列的构造器
    public ArrayQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        front = -1;
        rear = -1;
        arr = new int[arrMaxSize];
    }

    //判断队列是否满
    public boolean isFull() {
        return rear == maxSize-1;
    }

    //判断队列是否空
    public boolean isEmpty() {
        return front == rear;
    }

    //往队列中添加数据
    public void addQueue(int x) {
        if (isFull()) {
            System.out.println("队列已满，无法添加数据");
        }
        rear++;
        arr[rear] = x; //arr[++rear] = x; i++:先赋值再自增； ++i:先自增再赋值
    }

    //从队列中提取数据
    public int getQueue() throws Exception {
        if (isEmpty()) {
            throw new RuntimeException("队列为空，请先添加数据");
        }
        front++;
        return arr[front];
    }

    //显示队列的所有数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空，无法读取数据！");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]: %d\n",i,arr[i]);
        }
    }

    //显示队列的头数据
    public int getFront() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空，无头数据");
        }
        return arr[front+1]; //不可++front，否则会改变front的值
    }
}